<template>
    <div class="order-detail" v-loading="maintenanceStore.loading">
        <order-banner @processClick="processClick" />
        <div class="order-main">
            <div class="left">
                <order-tree @handlerNode="handlerNode" ref="orderTreeRef" v-show="isShowComponent" :isShowComponent="isShowComponent" />
                <order-tree @handlerNode="repairHandlerNode" ref="repairTreeRef" v-show="!isShowComponent" :isShowComponent="isShowComponent" />
            </div>
            <div class="right">
                <component
                    :is="isShowComponent ? associationPolicy : reportDetail"
                    :tableConfig="maintenanceStore.stateOperation === 1 ? tableLookConfig : tableConfig"
                    :isShowTitle="true"
                    :titleText="title"
                    @handler="handler"
                    ref="associationRef"
                    @radioChange="radioChange"
                    @preSave="preSave"
                    @handlderNormal="handlderNormal"
                ></component>
            </div>
        </div>
        <div class="btns" v-if="maintenanceStore.stateOperation !== 1">
            <el-button type="primary" class="confrim" @click="leftBtnClick">{{ btnText.left }}</el-button>
            <w-button :isShowIcon="false" @click="rightBtnClick" v-if="btnText.right">{{ btnText.right }}</w-button>
        </div>

        <w-popup :isShowPopup="isShowExaminePopup" @close="isShowExaminePopup = false" @confrim="isShowExaminePopup = false" confrimText="确定" cancelText="取消">
            <template #top>
                <div style="color: #1b3646" class="notice-two">
                    <i class="iconfont icon-jinggaotishi" style="color: #ffc53f"></i>
                    <span>尚有未完成检查项，请完成后提交！</span>
                </div>
            </template>
            <template #bottom>
                <div style="color: #1b3646" class="notice-one">
                    <span>提示</span>
                    <i class="iconfont icon-yujing icon" style="color: #ffde92"></i>
                    <span>为未完成</span>
                </div>
            </template>
        </w-popup>
        <w-popup :isShowPopup="isShowProcessPopup" @close="isShowProcessPopup = false" @confrim="isShowProcessPopup = false" width="800" :isShowCancel="false" class="process" confrimText="确定">
            <order-process></order-process>
        </w-popup>
        <w-popup :isShowPopup="isShowStatic" @close="isShowStatic = false" width="800" :isShowCancel="false" class="process" confrimText="确定" title="1" @confrim="staticConfrim" :loading="loading">
            <template #title>
                <span>本次检查共有</span>
                <span style="color: #ff5d84">{{ tableDataLength }}</span>
                <span>处异常</span>
            </template>
            <w-table ref="staticTableRef" :isShowPagination="false" :propTableConfig="staticTableConfig"></w-table>
        </w-popup>
    </div>
</template>

<script setup>
import orderBanner from "./cpn/orderBanner.vue";
import wButton from "@/components/wButton.vue";
import orderProcess from "./cpn/orderProcess.vue";
import associationPolicy from "./cpn/associationPolicy.vue";
import orderTree from "./cpn/orderTree.vue";
import wTable from "@/components/wTable.vue";
import reportDetail from "./cpn/reportDetail.vue";
import { tableConfig, staticTableConfig, tableLookConfig } from "./config.js";
import { ref, nextTick, provide, onUnmounted } from "vue";
import { setMaintenance, preSaveMaintenance, preGetMaintenance } from "@/service/api/maintenance.js";
import { mainStore } from "@/store/main.js";
import { useMaintenance } from "@/store/maintenance.js";
import { cloneDeep } from "@/utils/utils.js";
import { useRouter } from "vue-router";
import { BASE_URL } from "@/service/request/config";

const mStore = mainStore();
const router = useRouter();
const associationRef = ref([]);
const maintenanceStore = useMaintenance();
const repairTreeRef = ref(null);
preGetMaintenance(mStore.tableData.id).then((res) => {
    if (res.code === 200) {
        maintenanceStore.reportTreeData = res.data;
        recursionData(maintenanceStore.reportTreeData);
        maintenanceStore.reportTreeData.forEach((item) => {
            item.leftHot = item.childs.reduce((a, b) => a + b.leftHot, 0);
            item.rightHot = item.childs.reduce((a, b) => a + b.rightHot, 0);
        });
        function recursionData(arr) {
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].depth === 1) {
                    arr[i].rightHot = arr[i].items.length;
                    arr[i].remark = arr[i].remark;
                    arr[i].imgList = arr[i].images.map((item) => ({ id: item.id, url: BASE_URL + item.path }));
                    arr[i].tableData = arr[i].items;
                    arr[i].tableData.forEach((item) => {
                        item.dsposalMethod = item.disposalMethodText?.split(";").map((item) => ({ label: item, value: item }));
                        item.inspectionResult = item.inspectionResultText?.split(";").map((item) => ({ label: item, value: item }));
                        item.checked = item.checkInspectionResult;
                        item.handle = item.checkDisposalMethod;
                        item.disable = item.checked === "否" || item.checked === "无" ? true : false;
                    });
                    arr[i].leftHot = arr[i].items.filter((item) => item.checked && item.handle && (item.checked !== "否" || item.checked !== "无")).length;
                }
                if (!arr[i].childs.length) continue;
                recursionData(arr[i].childs);
            }
        }
    }
});
maintenanceStore.getDeviceTree(mStore.tableData.id, () => {
    maintenanceStore.treeSelectNode = maintenanceStore.treeData[0].childs[0];
    associationRef.value.tableRef.tableData = maintenanceStore.treeSelectNode.items;
    nextTick(() => {
        orderTreeRef.value.treeCpnRef.treeRef.setCurrentKey(maintenanceStore.treeSelectNode.id, true);
    });
    title.value = [maintenanceStore.treeData[0].name, maintenanceStore.treeSelectNode.name];
    recursionData(maintenanceStore.treeData);
    function recursionData(arr) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].depth === 0) {
                arr[i].hot = arr[i].childs.reduce((p, a) => p + a.hot, 0);
                arr[i].childs.every((item) => item.isShowCross) ? (arr[i].isShowCross = true) : (arr[i].isShowCross = false);
                arr[i].childs.some((item) => item.isShowChoose) ? (arr[i].isShowChoose = true) : (arr[i].isShowChoose = false);
            }
            if (!arr[i].childs.length) continue;
            recursionData(arr[i].childs);
        }
    }
});
const title = ref([]);
const repairHandlerNode = (node) => {
    if (node.level !== 1) {
        associationRef.value.associationPolicyRef.tableRef.tableData = node.data.tableData;
        maintenanceStore.treeSelectNode = node.data;
    }
};
const handlerNode = (node) => {
    if (node.level !== 1) {
        associationRef.value.tableRef.tableData = node.data.items;
        maintenanceStore.treeSelectNode = node.data;
        title.value = [node.parent.data.name, node.data.name];
    } else {
        title.value = [];
        associationRef.value.tableRef.tableData = [];
        maintenanceStore.treeSelectNode = {};
    }
};
const orderTreeRef = ref(null);
const isShowComponent = ref(true);
const handler = () => {
    isShowComponent.value = false;
    btnText.value.left = "保存";
    btnText.value.right = "取消";
    nextTick(() => {
        let find = null;
        maintenanceStore.reportTreeData.forEach((item) => {
            if (find) return;
            find = item.childs.find((item) => item.id === maintenanceStore.treeSelectNode.id);
        });
        maintenanceStore.treeSelectNode = find;
        associationRef.value.associationPolicyRef.tableRef.tableData = find.tableData;
        repairTreeRef.value.treeCpnRef.treeRef.setCurrentKey(find.id);
    });
};
const radioChange = (index, value) => {
    const selectData = orderTreeRef.value.treeCpnRef.treeRef.getCurrentNode();
    //当前选择父级
    const parentData = maintenanceStore.treeData.find((item) => item.id === selectData.parentId);
    if (value) {
        let parentDataCopy = null;
        const reportTreeP = maintenanceStore.reportTreeData.find((item) => item.id === parentData.id);
        //保存父级
        if (!reportTreeP) {
            parentDataCopy = cloneDeep(parentData);
            parentDataCopy.childs = [];
            maintenanceStore.reportTreeData.push(parentDataCopy);
            maintenanceStore.expanded = [parentDataCopy.id];
        } else {
            parentDataCopy = reportTreeP;
        }
        let find = null;
        maintenanceStore.reportTreeData.forEach((item) => {
            if (find) return;
            find = item.childs.find((item) => item.id === selectData.id);
        });
        //保存子级
        if (!find) {
            const selectDataCopy = cloneDeep(selectData);
            selectDataCopy.tableData = [];
            selectDataCopy.remark = "";
            selectDataCopy.imgList = [];
            selectDataCopy.leftHot = 0;
            parentDataCopy.childs.push(selectDataCopy);
            maintenanceStore.treeSelectNode = selectDataCopy;
            const tableDataCopy = cloneDeep(selectData.items[index]);
            tableDataCopy.dsposalMethod = tableDataCopy.disposalMethodText?.split(";").map((item) => ({ label: item, value: item }));
            tableDataCopy.inspectionResult = tableDataCopy.inspectionResultText?.split(";").map((item) => ({ label: item, value: item }));
            tableDataCopy.disable = false;
            tableDataCopy.checked = "";
            tableDataCopy.handle = "";
            selectDataCopy.tableData.push(tableDataCopy);
            selectDataCopy.rightHot = selectDataCopy.tableData.length;
            nextTick(() => {
                associationRef.value.associationPolicyRef.tableRef.tableData = selectDataCopy.tableData;
            });
            parentDataCopy.leftHot = parentDataCopy.childs.reduce((a, b) => a + b.leftHot, 0);
            parentDataCopy.rightHot = parentDataCopy.childs.reduce((a, b) => a + b.rightHot, 0);
        } else {
            maintenanceStore.treeSelectNode = find;
            selectData.items[index].dsposalMethod = selectData.items[index].disposalMethodText?.split(";").map((item) => ({ label: item, value: item }));
            selectData.items[index].inspectionResult = selectData.items[index].inspectionResultText?.split(";").map((item) => ({ label: item, value: item }));
            find.tableData.push(cloneDeep(selectData.items[index]));
            find.rightHot = find.tableData.length;
            nextTick(() => {
                associationRef.value.associationPolicyRef.tableRef.tableData = find.tableData;
            });
        }
        if (reportTreeP) {
            reportTreeP.leftHot = reportTreeP.childs.reduce((a, b) => a + b.leftHot, 0);
            reportTreeP.rightHot = reportTreeP.childs.reduce((a, b) => a + b.rightHot, 0);
        }
        selectData.items[index].parentName = parentData.name;
        maintenanceStore.expanded = [];
        nextTick(() => {
            repairTreeRef.value.treeCpnRef.treeRef.setCurrentKey(maintenanceStore.treeSelectNode.id, true);
        });
        isShowComponent.value = false;
        btnText.value.left = "保存";
        btnText.value.right = "取消";
    } else {
        const p = maintenanceStore.reportTreeData.find((item) => item.id === parentData.id);
        const pIndex = maintenanceStore.reportTreeData.findIndex((item) => item.id === parentData.id);
        const find = p?.childs.find((item) => item.id === selectData.id);
        if (find) {
            find.rightHot = find.tableData.length;
            find.leftHot = find.tableData.filter((item) => item.checked && item.handle).length;
            find.tableData?.splice(index, 1);
            if (!find.tableData.length) {
                maintenanceStore.reportTreeData.splice(pIndex, 1);
            }
        }
        if (p) {
            p.leftHot = p.childs.reduce((a, b) => a + b.leftHot, 0);
            p.rightHot = p.childs.reduce((a, b) => a + b.rightHot, 0);
        }
    }
    selectData.hot = selectData.items.filter((item) => item.isRadio).length;
    selectData.isShowCross = selectData.items.every((item) => !item.isRadio && item.isRadio !== null);
    selectData.isShowChoose = selectData.items.some((item) => item.isRadio === null);
    parentData.hot = parentData.childs.reduce((a, b) => a + b.hot, 0);
    parentData.childs.every((item) => item.isShowCross) ? (parentData.isShowCross = true) : (parentData.isShowCross = false);
    parentData.childs.some((item) => item.isShowChoose) ? (parentData.isShowChoose = true) : (parentData.isShowChoose = false);
};
const handlderNormal = () => {
    const selectData = orderTreeRef.value.treeCpnRef.treeRef.getCurrentNode();
    const parentData = maintenanceStore.treeData.find((item) => item.id === selectData.parentId);
    selectData.isShowCross = selectData.items.every((item) => !item.isRadio && item.isRadio !== null);
    selectData.isShowChoose = selectData.items.some((item) => item.isRadio === null);
    parentData.childs.every((item) => item.isShowCross) ? (parentData.isShowCross = true) : (parentData.isShowCross = false);
    parentData.childs.some((item) => item.isShowChoose) ? (parentData.isShowChoose = true) : (parentData.isShowChoose = false);
};
const preSave = (model) => {
    maintenanceStore.loading = true;
    preSaveMaintenance(model)
        .then((res) => {
            maintenanceStore.loading = false;
            if (res.code === 200) {
                ElMessage({
                    message: "预保存成功",
                    type: "success"
                });
            }
        })
        .catch((err) => (maintenanceStore.loading.value = false));
};
const isShowExaminePopup = ref(false);
//弹窗数据
const isShowStatic = ref(false);
const staticTableRef = ref(null);
const tableDataLength = ref(0);
const leftBtnClick = () => {
    //维保详情提交
    if (isShowComponent.value) {
        let tableData = [];
        const isChoose = maintenanceStore.treeData.every((item) => !item.isShowChoose);
        if (!isChoose) {
            isShowExaminePopup.value = true;
        } else {
            const isCross = maintenanceStore.treeData.some((item) => !item.isShowCross);
            isShowStatic.value = true;
            if (isCross) {
                recursionData(maintenanceStore.treeData, (item) => (tableData = [...tableData, ...item.items.filter((item) => item.isRadio)]));
            } else {
                tableData = [];
            }
            tableDataLength.value = tableData.length;
            nextTick(() => {
                staticTableRef.value.tableData = tableData;
            });
        }
    } else {
        //报修详情提交
        btnText.value.left = "提交";
        btnText.value.right = "取消";
        isShowComponent.value = true;
        let find = null;
        maintenanceStore.treeData.forEach((item) => {
            if (find) return;
            find = item.childs.find((item) => item.id === maintenanceStore.treeSelectNode.id);
        });
        maintenanceStore.treeSelectNode = find;
        nextTick(() => {
            orderTreeRef.value.treeCpnRef.treeRef.setCurrentKey(maintenanceStore.treeSelectNode.id);
            associationRef.value.tableRef.tableData = find.items;
        });
    }
};

const rightBtnClick = () => {
    //维保详情提交
    if (isShowComponent.value) {
        isShowComponent.value = true;
        router.push("/main/maintenanceManage");
    } else {
        //报修详情提交
        isShowComponent.value = true;
        btnText.value.left = "提交";
        btnText.value.right = "取消";
        let find = null;
        maintenanceStore.treeData.forEach((item) => {
            if (find) return;
            find = item.childs.find((item) => item.id === maintenanceStore.treeSelectNode.id);
        });
        maintenanceStore.treeSelectNode = find;
        nextTick(() => {
            orderTreeRef.value.treeCpnRef.treeRef.setCurrentKey(maintenanceStore.treeSelectNode.id);
            associationRef.value.tableRef.tableData = find.items;
        });
    }
};
const staticConfrim = () => {
    maintenanceStore.loading = true;
    const maintenanceorderdetails = [];
    const repairDetails = [];
    recursionData(maintenanceStore.treeData, (item) => {
        if (item.items?.length) {
            const tableData = item.items.filter((item) => item.isRadio !== null).map((outItem) => ({ id: outItem.id, state: outItem.isRadio, secondStructureId: item.id }));
            maintenanceorderdetails.push(tableData);
        }
    });
    recursionData(maintenanceStore.reportTreeData, (item) => {
        repairDetails.push({
            structureId: item.id,
            picture: item.imgList.map((item) => item.id).join(","),
            remark: item.remark,
            repairDetailStrategies: item.tableData.map((item) => ({
                inspectionItemId: item.inspectionItemId,
                inspectionItemName: item.itemName,
                inspectionResult: item.checked,
                suggestDisposalMethod: item.handle
            }))
        });
    });
    setMaintenance({
        orderId: mStore.tableData.id,
        maintenanceorderdetails: maintenanceorderdetails.flat(),
        repairDetails
    })
        .then((res) => {
            maintenanceStore.loading = false;
            if (res.code === 200) {
                ElMessage({
                    message: "提交成功",
                    type: "success"
                });
                router.push("/main/maintenanceManage");
            }
        })
        .catch((err) => (maintenanceStore.loading = false));
};
const isShowProcessPopup = ref(false);
const processClick = () => {
    isShowProcessPopup.value = true;
};
const btnText = ref({ left: "提交", right: "取消" });
provide("isShowSelect", false);

function recursionData(arr, fn) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].depth) {
            fn(arr[i]);
        }
        if (!arr[i].childs.length) continue;
        recursionData(arr[i].childs, fn);
    }
}
onUnmounted(() => {
    maintenanceStore.treeData = [];
    maintenanceStore.reportTreeData = [];
    maintenanceStore.treeSelectNode = {};
});
</script>

<style lang="less" scoped>
.order-detail {
    font-size: 16px;
    .order-main {
        display: flex;
        margin-top: 16px;
        .left {
            box-sizing: border-box;
            margin-right: 16px;
            padding: 16px;
            min-width: 284px;
            height: 669px;
            background-color: #fff;
            overflow: auto;
        }
        .right {
            box-sizing: border-box;
            flex: 1;
            width: 0;
            padding: 16px;
            height: 669px;
            background-color: #fff;
            overflow: auto;
        }
    }
    .btns {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 16px;
        height: 64px;
        background-color: #fff;
        .confrim {
            width: 80px;
            height: 32px;
        }
    }
    .notice-one {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 10.08px;
        margin-bottom: 16px;
        font-size: 14.08px;
        color: #8c8c8c;
        .icon {
            margin: 0 4px;
        }
    }
    .notice-two {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 16px;
        font-weight: 600;
        color: #1b3646;
        i {
            margin-right: 10.08px;
        }
    }

    .process {
        ::v-deep(.btns) {
            justify-content: flex-end;
        }
    }
}
</style>
